﻿//  --------------------------------
//  Copyright (c) AW Systems, Inc. All rights reserved.
//  This source code is made available under the terms of the Microsoft Public License (Ms-PL)
//  http://www.codeplex.com/SLAM/license
//  ---------------------------------

using System;
using System.Data.Linq;
using System.Linq;
using AWS.SLAM.Administration.Data;
using AWS.SLAM.Configuration;
using Microsoft.SharePoint;
using System.Web;

namespace AWS.SLAM.Administration
{
    public partial class Diagnostics : System.Web.UI.Page
    {
        private string slamFolder = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            //if under a site collection other than the root, doing a simple
            //redirect to the page will always redirect to the root, so the desired
            //location needs extracted from the RawUrl
            slamFolder = Request.RawUrl.Substring(0, Request.RawUrl.LastIndexOf("/") + 1);

            if (!IsPostBack)
            {
                //Test if the 3.5 Framework is installed
                if (!InstallationValidator.VerifyNetFx35IsInstalled())
                {
                    Response.Redirect(slamFolder + "SLAMControlPanel.aspx");
                }
                else
                {
                    //Test if SLAM can clear instances, if it cannot go back to the Control Panel
                    try
                    {
                        ComponentService.ClearInstances();
                    }
                    catch
                    {
                        Response.Redirect(slamFolder + "SLAMControlPanel.aspx");
                    }
                }

                if (Request.UrlReferrer != null && (Request.UrlReferrer.ToString().EndsWith("Activation.aspx") || Request.UrlReferrer.ToString().EndsWith("Synchronization.aspx")))
                {
                    btnViewMessages_Click(this, e);
                }
                else
                {
                    messagesPanel.Visible = false;
                }
            }
            else
            {
                ComponentService.ClearInstances();
            }
        }


        /// <summary>
        /// Event handler for viewing Diagnostic Messages
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnViewMessages_Click(object sender, EventArgs e)
        {
            lblErrorMessages.Text = "";
            messagesPanel.Visible = true;
            optionsPanel.Visible = false;
            try
            {
                //Get SLAM configuration
                IConfigurationManager configuration = ComponentService.GetInstance<IConfigurationManager>();
                DataMapping currentDataMapping = configuration.DataMapping;
                string siteCollection = SPContext.GetContext(HttpContext.Current).Site.ServerRelativeUrl.TrimStart('/');
                string connectionString = "";
                if (!String.IsNullOrEmpty(siteCollection) && configuration.DataMappings.ContainsKey(siteCollection))
                {
                    currentDataMapping = configuration.DataMappings[siteCollection];
                }
                if (configuration is XmlConfigurationManager)
                {   
                    connectionString = ((XmlSqlDataMapping)currentDataMapping).GetConnectionString();
                }

                if (String.IsNullOrEmpty(connectionString))
                {
                    connectionString = configuration.GetSection<ConnectionStringSection>("ConnectionStrings").Default;
                }
                else
                {
                    connectionString = configuration.GetSection<ConnectionStringSection>("ConnectionStrings").GetConnectionString(connectionString);
                }

                
                DataContext dataContext = new DataContext(connectionString);

                //Verify connection exists for default connection string
                //if it does, bind top error messages, if not display an error message
                try
                {
                    bool messageTableExists = dataContext.ExecuteQuery<int>(Queries.VerifyMessageLogExists).FirstOrDefault() > 0;
                    if (messageTableExists)
                    {
                        //Bind the latest 50 messages from the last 30 days to the Top Error Messages repeater.  
                        //Filter out messages that simply record the "Trace Level" the SLAM logger is logging.
                        gvTopErrorMessages.DataSource = dataContext.ExecuteQuery<SLAMMessage>(Queries.RetrieveRecentMessageLogMessages);
                        gvTopErrorMessages.DataBind();
                    }
                }
                catch (Exception ex)
                {
                    lblErrorMessages.Text = "SLAM is attempting to connect to the database using the Default connection string defined in the SLAM configuration file but is failing to connect.  It is receiving the following error:<br /><br />" + ex.Message;
                    gvTopErrorMessages.Visible = false;
                }
            }
            catch (Exception ex)
            {
                lblErrorMessages.Text = ex.ToString();
                gvTopErrorMessages.Visible = false;
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect(slamFolder + "SLAMControlPanel.aspx");
        }
    }
}
